<template>
  <div class="play-audio tac lh1 bsb por zi1 ovh" :class="isWx ? 'h100' : 'vh100'">
    <img class="gs-bg poa t0 l0" :src="audioBgimg"/>
    <div class="gs-bg-div poa t0 l0 w100 h100"></div>
    <div class="por zi-10">
      <div class="image dib vam bsb">
        <img :src="audioBgimg" class="resource-img vam w100 h100 cd-play" :class="{'stop-animation': !playing}">
      </div>
      <div class="resource-title">{{currResource.name}}</div>
      <div class="resource-remark">
        <span>主讲：{{currResource.teacher_name}}</span>
        <span>学习人数：{{(currResource.record_count / 10000).toFixed(2)}}万</span>
      </div>

      <div class="pof ctrl b0 l0 w100">
        <div class="first-row flex jcb aic">
          <div class="row-1-left flex aic">
            <img class="clock vam" src="../../images/audio/icon_clock.png" @click="togglePopup('clock')"/>
            <div class="speed wsnw" @click="togglePopup('speed')">{{popup.speed < 1 ? (popup.speed + '').slice(1) :
              popup.speed}}X
            </div>
            <img class="pay-vip vam" src="../../images/audio/vip_btn.png" @click="$router.push('/payvip/1')"/>
          </div>
          <img class="star vam" @click="collecting" :src="icons.collection[+currResource.is_collection]"/>
        </div>
        <div class="second-row flex jcb aic">
          <div class="start-time">{{currentTime}}</div>
          <div class="line flex-1" @click='changeProgress'>
            <div class="line-inner h100" :style="{width: progress + '%'}"></div>
          </div>
          <div class="total-time">{{duration}}</div>
        </div>
        <div class="third-row flex jcb aic">
          <img :src="icons.playType[+playType]" alt="" class="play-type vam" @click="changePlayType"/>
          <div class="play-ctrl">
            <img src="../../images/audio/icon_prev.png" @click="togglePlay(-1)" alt="" class="play-prev vam"/>
            <img :src="icons.play[+playing]" @click="togglePlay(0)" alt="" class="play-toggle vam"/>
            <img src="../../images/audio/icon_next.png" @click="togglePlay(1)" alt="" class="play-next vam"/>
          </div>
          <img src="../../images/audio/icon_list.png" alt="" class="show-list vam" @click="togglePopup('list')"/>
        </div>
      </div>
    </div>
    <van-popup v-model="popup.show" position="bottom" style="background-color: #161618;">
      <div class="popup-box">
        <div class="popup-title por tac">
          {{popup.type === 'clock' ? (popup.clock || popup.title) + '停止播放' : popup.title}}
          <img v-show="popup.close" @click="togglePopup" class="popup-close abs-m r0"
               src="../../images/audio/icon_close_03.png"/>
        </div>
        <div class="popup-res ova" v-show="popup.type === 'list'">
          <div class="popup-res-item flex jcb aic" :class="{'popup-res-item-act': currResource.id === item.id}"
               @click="changeCurrAudio(item)"
               v-for="(item, i) in resourceList" :key="i">
            <div class="flex aic " :style="{width: !userInfo.is_vip ? '18.5rem' : ''}">
              <img src="../../images/audio/icon_sound_03.png" v-show="currResource.id === item.id"
                   class="popup-sound vam">
              <div class="popup-res-title flex-1 wot1 tal">{{item.name}}</div>
            </div>
            <vip-tip v-show="!userInfo.is_vip" class="tip" free-text="试听" :is-vip="!item.is_free"></vip-tip>
          </div>
        </div>
        <div class="popup-clock" v-show="popup.type === 'clock'">
          <div class="popup-clock-box" v-for="(box, i) in autoList" :key="i">
            <div class="popup-clock-title flex jcb aic">
              <span>{{!i ? '定时' : '定集'}}停止播放</span>
              <van-switch active-color="#1bcee4" inactive-color="#3c3c43" size="1.38rem"
                          @input="setAutoType('switch', i)"
                          :value="popup.autoType && (!i ? typeof popup.autoType === 'number': typeof popup.autoType === 'string')"/>
            </div>
            <div class="popup-clock-list flex">
              <div class="popup-clock-item dib vam flex-col jce aic"
                   @click="setAutoType(i, j)"
                   :class="{active: popup.autoType === item, item1: i}" v-for="(item, j) in box" :key="j">
                <span>{{i ? item + '集' : item}}</span>
                <span v-show="!i" class="unit">分钟</span>
              </div>
            </div>
          </div>
        </div>
        <div class="popup-speed flex jcb" v-show="popup.type === 'speed'">
          <div class="popup-speed-item wsnw" @click="speedChange(item)" :class="{active: item === popup.speed}"
               v-for="(item, i) in speedList" :key="i">
            {{item % 1 ? item : (item + '.0')}}X
          </div>
        </div>
      </div>
    </van-popup>
    <!--  -->
    <audio :src="currResource.cn_url" ref="audio" autoplay @play="audioPlay" @pause="audioPause"
           @timeupdate="audioUpdate" @durationchange="durationchange" @ended="audioEnd" @loadeddata="audioLoad"></audio>
  </div>
</template>

<script>
  import { mapGetters, mapMutations } from 'vuex';

  export default {
    name: 'PlayAudio',
    data() {
      return {
        audio: null,

        icons: {
          play: [
            require('../../images/audio/icon_play.png'),
            require('../../images/audio/icon_stop.png')
          ],
          playType: [
            require('../../images/audio/icon_return.png'),
            require('../../images/audio/icon_danqu.png')
          ],
          collection: [
            require('../../images/audio/icon_star.png'),
            require('../../images/audio/icon_star_act_1.png')
          ]
        },
        playing: false,
        playType: 0,

        popup: {
          type: '',
          show: false,
          close: false,
          title: '',
          clock: '',
          speed: 1,
          time: 0,
          autoType: ''
        },
        timer: null,
        speedList: [.75, 1, 1.25, 1.5, 2],
        autoList: [
          [10, 20, 30],
          ['01', '02', '03']
        ],

        currResource: {
          teacher_name: '格林教育',
          record_count: '0',
          is_collection: 0
        },
        resourceList: [],
        cId: '',
        rId: '',
        rName: '',
        curr: 1,
        limits: 100,
        currentTime: '00:00',
        duration: '00:00',
        progress: 0,
        nextId: '',
        episodeNumber: 0, // 定集数
        playNum: 0, // 播放次数
        isNum: false, // 是否开启定集
        audioBgimg: require('@/images/logo.png'),
        total_time: 0,
        playback_time: 0
      };
    },
    computed: {
      ...mapGetters(['userInfo', 'productInfo', 'hasAudio', 'isWx'])
    },
    methods: {
      ...mapMutations(['setCurrAudio']),
      // 获取音频
      getAudio(rid, name) {
        this.rId = rid;
        this.http.$post('api/resource.resources_jd/get_format_resource_details', {
          resources_id: rid,
          resources_name: name,
          uid: this.userInfo.uid,
          product_id: this.productInfo.product_id
        }).then(res => {
          this.nextId = res.next_resource_id;
          this.currResource = res;
          let obj = {
            title: res.name,
            desc: `我正在学习${res.name}，老师讲得很好，通俗易懂，裂墙推荐！`,
            imgUrl: this.audioBgimg,
            link: this.util.makeShareLink(),
            success: () => {
              // 设置成功
              // this.$toast.success('分享成功');
            }
          };
          wx.ready(() => {
            wx.updateAppMessageShareData(obj);
            wx.updateTimelineShareData(obj);
          });
        }).catch(err => {
          if (+err.code === 10020) {
            this.util.goToPlay({});
          } else {
            this.$err(err);
          }
        });
      },
      // 获取课程图片
      getCourse() {
        this.http.$post('api/resource.course/get_jd_course_list', {
          course_id: this.cId
        }).then(res => {
          this.audioBgimg = res.list[0].bigimg;
        });
      },
      // 获取播放时长
      audioUpdate() {
        this.playback_time = Math.ceil(this.audio.currentTime);
        this.currentTime = this.util.numberToTime(this.audio.currentTime * 1000, 'mm:ss');
        this.progress = this.audio.currentTime / this.audio.duration * 100 | 0;
      },
      durationchange() {
        this.total_time = Math.ceil(this.audio.duration);
        this.duration = this.util.numberToTime(this.audio.duration * 1000, 'mm:ss');
      },
      // 开始播放
      audioPlay() {
        this.playing = true;
      },
      // 暂停
      audioPause() {
        this.playing = false;
        if (this.userInfo.uid) {
          this.addPlayback();
        }
      },
      // 播放结束
      audioEnd() {
        this.setOperation();
      },
      // 改变进度条
      changeProgress(data) {
        this.progress = data.offsetX / 267 * 100 | 0;
        this.audio.currentTime = this.progress * this.audio.duration / 100;
      },
      // 下一首
      nextSet() {
        this.audio.pause();
        if (this.nextId) {
          this.getAudio(this.nextId);
        } else {
          this.getAudio(this.resourceList[0].id);
        }
      },
      // 上一首
      previousSet() {
        let isTrue = this.resourceList.some((val, idx) => {
          return val.id === +this.rId && idx > 0;
        });
        if (isTrue) {
          this.getAudio(this.rId - 1);
        } else {
          this.getAudio(this.resourceList[this.resourceList.length - 1].id);
        }
      },
      // 已加载音频，获取数据
      audioLoad() {
        this.audio.playbackRate = this.popup.speed;
        if (this.userInfo.uid) {
          this.addRecord();
          this.addCourseRecord();
          this.addPlayTimes();
        }
        this.audio.play(); // 部分手机设备不支持自动播放,采取调用play()来达到自动播放效果
        this.setCurrAudio(+this.rId);
      },
      // 播放速度改变
      speedChange(speed) {
        this.popup.speed = speed;
        this.audio.playbackRate = speed;
      },
      // 定集操作
      setOperation() {
        if (this.isNum) {
          this.playNum++;
          if (this.playNum === this.episodeNumber) {
            this.audio.pause();
            this.clockEnd();
            this.playNum = 0;
            this.$toast('定集结束');
          } else {
            this.popup.clock = (this.episodeNumber - this.playNum) + '集后';
            this.nextSet();
          }
        } else {
          this.nextSet();
        }
      },
      // 定时结束
      clockEnd() {
        let popup = this.popup;
        clearInterval(this.timer);
        this.timer = null;
        this.episodeNumber = 0;
        this.isNum = false;
        popup.time = 0;
        popup.clock = '';
        popup.autoType = '';
        // 停止播放..
      },

      // 选择定时
      setAutoType(type, index) {
        let popup = this.popup;
        let curr = '';
        if (type === 'switch') {
          if (popup.autoType && (index && typeof popup.autoType === 'string' || !index && typeof popup.autoType === 'number')) {
            this.clockEnd();
          } else {
            this.setAutoType(index, 0);
          }
        } else {
          curr = this.autoList[type][index];
          if (curr !== popup.autoType) {
            this.clockEnd();
            switch (typeof curr) {
              case 'string':
                // 定集
                this.isNum = true;
                this.episodeNumber = +curr;
                this.playNum = 0;
                popup.clock = +curr + '集后';
                break;
              case 'number':
                // 定时
                popup.time = curr * 60 * 1000;
                popup.clock = this.util.numberToTime(popup.time, 'mm:ss') + '后';
                this.timer = setInterval(() => {
                  popup.time -= 1000;
                  popup.clock = this.util.numberToTime(popup.time, 'mm:ss') + '后';
                  if (popup.time <= 0) {
                    this.audio.pause();
                    this.clockEnd();
                  }
                }, 1000);
                break;
            }
          } else {
            curr = '';
          }
          popup.autoType = curr;
        }
      },

      // 选择音频
      changeCurrAudio(item) {
        this.getAudio(item.id, item.name);
      },

      // 获取课时列表
      getResourceList() {
        this.http.$post('api/resource.resources_jd/get_resources_list', {
          curr: this.curr,
          limits: this.limits,
          course_id: this.cId || '',
          product_id: this.productInfo.product_id
        }).then(res => {
          this.resourceList.push(...res.list);
        });
      },

      // 获取课时详情
      getResourceInfo() {
        Object.assign(this.currResource, this.resourceList[2]);
      },

      // 切换插入状态
      togglePlay(bool) {
        // 开始播放 0：当前 <0: 上bool首 >0: 下bool首
        switch (bool) {
          case 1:
            this.nextSet();
            break;
          case -1:
            this.previousSet();
            break;
          default:
            this.playing ? this.audio.pause() : this.audio.play();
        }
      },
      // 切换播放循环
      changePlayType(num) {
        this.playType = typeof num === 'number' ? num : (++this.playType % this.icons.playType.length);
        this.playType ? this.$toast('循环播放') : this.$toast('列表播放');
        this.audio.loop = this.playType;
      },
      // 改变收藏状态
      collecting() {
        if (this.userInfo.uid) {
          this.http.$post('api/user/save_course_collection', {
            uid: this.userInfo.uid,
            course_id: this.cId,
            product_id: this.productInfo.product_id
          }).then(res => {
            this.currResource.is_collection = res.status === 1 ? 1 : 0;
          }).catch(this.$err);
        } else {
          this.$router.push({
            name: 'Login'
          });
        }
      },
      // 切换打开popup
      togglePopup(type) {
        let popup = this.popup;
        popup.close = false;
        switch (type) {
          case 'clock':
            if (popup.autoType) {
              if (typeof popup.autoType === 'string') {
                popup.clock = (popup.clock ? popup.clock : popup.autoType) + '集后';
              } else {
                popup.clock = this.util.numberToTime(popup.time, 'mm:ss') + '后';
              }
            } else {
              popup.title = '未开启自动';
            }
            break;
          case 'speed':
            popup.title = '播放速度';
            break;
          case 'list':
            popup.title = '播放列表';
            popup.close = true;
            break;
          default:
            console.log(type);
        }
        popup.type = type;
        popup.show = !popup.show;
      },
      // 添加课时播放时长
      addPlayback() {
        let params = {
          uid: this.userInfo.uid,
          resource_id: this.rId,
          total_time: this.total_time | 0,
          playback_time: this.playback_time | 0
        };
        this.http.$post('api/user/add_playback_length', params).then(res => {
          // console.log(res)
        }).catch(this.$err);
      },
      // 添加播放时长记录
      addPlayTimes() {
        let params = {
          uid: this.userInfo.uid,
          resources_id: this.rId,
          times: this.total_time | 0,
          ...this.productInfo
        };
        this.http.$post('api/user/add_video_play_times', params).then(res => {
          // console.log(res)
        }).catch(this.$err);
      },
      // 添加观看记录
      addRecord() {
        let params = {
          uid: this.userInfo.uid,
          resource_id: this.rId,
          type: 1,
          ...this.productInfo
        };
        this.http.$post('api/user/add_resources_record', params).then(res => {
          // console.log(res)
        }).catch(this.$err);
      },
      // 添加课程播放记录
      addCourseRecord() {
        let params = {
          course_id: this.cId,
          ...this.productInfo
        };
        this.http.$post('api/user/add_course_record', params).then(res => {
          // console.log(res)
        }).catch(console.log);
      }
    },

    created() {
      if (!this.hasAudio) {
        return this.$router.replace('/notchannel');
      }
      this.rId = this.$route.params.rId;
      this.rName = this.$route.params.rName;
      this.cId = this.$route.params.cId;
      this.getCourse();
      this.getAudio(this.rId, this.rName);
      this.getResourceList();
      this.util.setWxConfig([
        'updateAppMessageShareData',
        'updateTimelineShareData'
      ]).catch(console.log);
    },
    mounted() {
      this.audio = this.$refs.audio;
    }
  };
</script>

<style scoped lang="less">
  @keyframes cd-play-animation {
    0% {
      transform: rotate(0);
    }
    100% {
      transform: rotate(360deg);
    }
  }

  .play-audio {
    padding-top: 3rem;
    color: #fff;
    .cd-play {
      animation: cd-play-animation 6s infinite linear;
    }
    .gs-bg {
      z-index: 0;
      width: 100vh;
      height: 100vw;
      transform-origin: left top;
      transform: rotate(90deg) translateY(-100%);
      filter: blur(3rem);
      &-div {
        background-color: rgba(46, 42, 63, .75);
      }
    }
    .image {
      margin-bottom: 0.88rem;
      padding: 2.56rem;
      width: 15.63rem;
      height: 15.63rem;
      background: url(../../images/audio/icon_cd.png) no-repeat center center / 100% 100%;
    }
    .resource- {
      &img {
        border-radius: 50%;
      }
      &title {
        padding: 0 .5rem;
        margin-bottom: .71rem;
        font-size: 1.13rem;
      }
      &remark {
        font-size: .75rem;
        opacity: .5;
        > :last-child {
          margin-left: 1.88rem;
        }
      }
    }

    .ctrl {
      padding-bottom: 1.25rem;
      .first-row {
        margin: 0 1.88rem 1.84rem;
      }
      .clock {
        width: 1.25rem;
        height: 1.25rem;
      }
      .speed {
        margin: 0 1.5rem;
        width: 2rem;
        font-size: .75rem;
        line-height: 1.01rem;
        border-radius: .19rem;
        border: .06rem solid rgba(255, 255, 255, .4);
      }
      .pay-vip {
        width: 3.63rem;
        height: 1.13rem;
      }
      .star {
        width: 1.34rem;
        height: 1.28rem;
      }
      .second-row {
        margin: 0 .94rem 1.25rem;
        font-size: .63rem;
        color: rgba(255, 255, 255, .5);
      }
      .line {
        margin: 0 .47rem;
        height: .06rem;
        background-color: rgba(213, 213, 213, .5);
        &-inner {
          background-color: #51bac8;
        }
      }
      .third-row {
        margin: 0 1.88rem;
      }
      .play-type {
        width: 1.44rem;
        height: 1.25rem;
      }
      .play-prev, .play-next {
        width: 1rem;
        height: 1.13rem;
      }
      .play-toggle {
        margin: 0 2.22rem;
        width: 3.06rem;
        height: 3.06rem;
      }
      .show-list {
        width: 1.25rem;
        height: 1.13rem;
      }
    }

    .van-popup {
      background-color: transparent;
    }

    .popup- {
      &box {
        padding: 0 .94rem;
        border-radius: .75rem .75rem 0 0;
        opacity: .98;
      }
      &title {
        font-size: .94rem;
        line-height: 3.09rem;
      }
      &close {
        right: .31rem;
        width: .94rem;
        height: .94rem;
      }
      &res {
        color: #868393;
        font-size: .88rem;
        line-height: 2.91rem;
        height: 17.69rem;
        border-top: .06rem solid rgba(255, 255, 255, .2);
        &-title {
          // width: 80%;
        }
        &-item {
          padding-right: .75rem;
          &:not(:last-child) {
            border-bottom: .06rem solid #2e2e30;
          }
          &-act {
            color: #0bcae2;
          }
        }
      }
      &sound {
        width: 1.16rem;
        margin-right: .53rem;
      }

      &clock {
        padding-bottom: .94rem;
        &-box {
          background-color: #2d2d32;
          border-radius: .38rem;
          &:not(:last-child) {
            margin-bottom: .63rem;
          }
        }
        &-title {
          padding: 0 .97rem;
          line-height: 2.72rem;
          border-bottom: .06rem solid rgba(255, 255, 255, .1);
        }
        &-list {
          padding: .94rem;
        }
        &-item {
          width: 3.31rem;
          height: 3.56rem;
          border-radius: .25rem;
          border: solid .06rem #424247;
          color: rgba(255, 255, 255, .7);
          font-size: 1rem;
          &:not(:last-child) {
            margin-right: .94rem;
          }
          &.item1 {
            width: 3.06rem;
            height: 3.06rem;
            font-size: .88rem;
            &:not(:last-child) {
              margin-right: 1.19rem;
            }
          }
          &.active {
            background-color: rgba(255, 255, 255, .2);
            border-color: rgba(255, 255, 255, .2);
          }
          .unit {
            font-size: .75rem;
            color: rgba(255, 255, 255, .4);
          }
        }
      }

      &speed {
        padding: 1.25rem .47rem;
        border-top: .06rem solid rgba(255, 255, 255, .1);
        &-item {
          width: 3.38rem;
          line-height: 3.06rem;
          border-radius: .25rem;
          border: solid .06rem #424247;
          font-size: .88rem;
          color: rgba(255, 255, 255, .7);
          &.active {
            background-color: rgba(255, 255, 255, .2);
          }
        }
      }
    }
  }
</style>
